package cn.edu.jnu.supershopper;


import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.core.app.ActivityCompat;

import net.tsz.afinal.FinalActivity;


public class EditBookActivity extends FinalActivity {
    public static final int RESULT_CODE_SUCCESS = 666;
    private int position;
    MyImageView BookCover;
    String imagePath;
    Spinner spinner;
    String label = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);
        initView();
        //请求权限
        if (ActivityCompat.checkSelfPermission(EditBookActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(EditBookActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }

        position= this.getIntent().getIntExtra("position",0);
        String name=this.getIntent().getStringExtra("name");
        int cover=this.getIntent().getIntExtra("cover",0);
        String isbn=this.getIntent().getStringExtra("isbn");
        String author=this.getIntent().getStringExtra("author");
        String published=this.getIntent().getStringExtra("published");
        String publishing=this.getIntent().getStringExtra("publishing");
        String score=this.getIntent().getStringExtra("score");
        String author_info=this.getIntent().getStringExtra("author_info");
        String description=this.getIntent().getStringExtra("description");
        String URL=this.getIntent().getStringExtra("URL");

        imagePath=this.getIntent().getStringExtra("imagePath");

        BookCover=findViewById(R.id.edit_book_cover);
        EditText editName=findViewById(R.id.edit_name);
        EditText editIsbn=findViewById(R.id.edit_ISBN);
        EditText editAuthor=findViewById(R.id.edit_author);
        EditText editPublished=findViewById(R.id.edit_published);
        EditText editPublishing=findViewById(R.id.edit_Publishing);
        EditText editScore=findViewById(R.id.edit_doubanScore);
        EditText editDescription=findViewById(R.id.edit_description);
        EditText editauthor_info=findViewById(R.id.edit_author_info);

        if(name!=null){
            editName.setText(name);
            editIsbn.setText(isbn);
            editAuthor.setText(author);
            editPublished.setText(published);
            editPublishing.setText(publishing);
            editScore.setText(score);
            editDescription.setText(description);
            editauthor_info.setText(author_info);
            if(imagePath!=null){
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                BookCover.setImageBitmap(bitmap);}
            else {
                if(!URL.equals("暂无信息"))BookCover.setImageURL(URL);
                else BookCover.setImageResource(cover);
            }
        }

        BookCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSysAlbum();
            }
        });

        Button buttonOk=findViewById(R.id.button_ok);
        buttonOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("name",editName.getText().toString());
                bundle.putString("isbn",editIsbn.getText().toString());
                bundle.putString("author",editAuthor.getText().toString());
                bundle.putString("published",editPublished.getText().toString());
                bundle.putString("publishing",editPublishing.getText().toString());
                bundle.putString("score",editScore.getText().toString());
                bundle.putString("description",editDescription.getText().toString());
                bundle.putString("score",editPublishing.getText().toString());
                bundle.putString("author_info",editauthor_info.getText().toString());
                bundle.putString("imagePath",imagePath);
                bundle.putString("label",label);

                bundle.putInt("position",position);
                intent.putExtras(bundle);
                setResult(RESULT_CODE_SUCCESS,intent);
                EditBookActivity.this.finish();
            }
        });

        Button buttonCancel=findViewById(R.id.button_cancel);
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditBookActivity.this.finish();
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        handleImageOnKitKat(data);
    }

    public static int ALBUM_RESULT_CODE = 0x999 ;

    /**
     * 打开系统相册
     * 定义Intent跳转到特定图库的Uri下挑选，然后将挑选结果返回给Activity
     * */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, ALBUM_RESULT_CODE);
    }

    //根据条件的不同去获取相册中图片的url
    @TargetApi(value = 19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
        System.out.println(imagePath);
    }

    /**获取图片的路径*/
    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    /**展示图片*/
    private void displayImage(String imagePath_) {
        imagePath = imagePath_;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath_);
        BookCover.setImageBitmap(bitmap);
    }

    private void initView() {
        spinner = (Spinner) findViewById(R.id.label);

        String[] stringArray = getResources().getStringArray(R.array.spinnerclass);
        //新建一个数组适配器ArrayAdapter设置三个参数：上下文，下拉列表的样式，数据源
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, stringArray);
        //将适配器设置给Spinner
        spinner.setAdapter(adapter);

        //设置item的被选择的监听
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //当item被选择后调用此方法
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取我们所选中的内容
                label = parent.getItemAtPosition(position).toString();
            }

            //只有当patent中的资源没有时，调用此方法
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

}